import { ReactElement, useRef, useEffect, RefObject } from 'react'
import { Form, Input, Row, Col, DatePicker, Space, Button, FormInstance } from 'antd'
import moment, { Moment } from 'moment'
import style from './index.module.less'
import { ConditionSchema } from '@src/components/schema/condition'
import { formatEndDate, formatBeginDate } from '@src/assets/js/tool'
import qs from 'query-string';

const { Item } = Form

export function formatCondition (d: { [k: string]: any }): { condition: ConditionSchema[], caseno_desc?: string } {
  const r: { condition: ConditionSchema[], caseno_desc?: string } = {
    condition: []
  }
  if (typeof d.serieno === 'string') {
    r.condition.push({ k: 'serieno', o: 'like', v: `%${d.serieno}%` })
  }
  if (typeof d.begin === 'string' && /^\d+$/.test(d.begin)) {
    r.condition.push({ k: 'create_datetime', o: '>=', v: formatBeginDate(d.begin) })
  }
  if (typeof d.end === 'string' && /^\d+$/.test(d.end)) {
    r.condition.push({ k: 'create_datetime', o: '<=', v: formatEndDate(d.end) })
  }
  if (typeof d.caseno_desc === 'string') {
    r.caseno_desc = d.caseno_desc
  }
  return r
}

// 改变搜索条件
function changeSearch (d: { [k: string]: any }, params: {[k: string]: any}, setParams: (v: {[k: string]: any}) => void): void {
  if (d.date instanceof Array && d.date.length > 0) {
    d.begin = Math.floor((d.date[0] as Moment).valueOf() / 1000)
    d.end = formatEndDate(d.date[1] as Moment)
    delete d.date
  } else {
    d.begin = undefined
    d.end = undefined
  }
  const keys = ['serieno']
  keys.forEach(key => {
    if (d[key] === undefined) {
      d[key] = undefined
    }
  })
  d.page = 1
  setParams({
    ...params,
    ...d
  })
}

function initForm (params: {[k: string]: any}, formRef: RefObject<FormInstance>): void {
  const c = formRef.current
  if (c === null) {
    return undefined
  }
  const o = qs.parse(qs.stringify(params))
  const r: { [k: string]: any } = {}
  if (typeof o.serieno === 'string') {
    r.serieno = o.serieno
  }
  if (typeof o.caseno_desc === 'string') {
    r.caseno_desc = o.caseno_desc
  }
  if (typeof o.begin === 'string' && /^\d+$/.test(o.begin) && typeof o.end === 'string' && /^\d+$/.test(o.end)) {
    r.date = [moment(parseInt(o.begin) * 1000), moment(parseInt(o.end) * 1000)]
  }
  c.setFieldsValue(r)
}

interface Props {
  params: {[k: string]: any}
  setParams: (v: {[k: string]: any}) => void
}

function Main ({params, setParams}: Props): ReactElement {
  const ref = useRef<FormInstance>(null)
  useEffect(() => {
    initForm(params, ref)
  }, [params])
  return (
    <div className={style.container}>
      <Form ref={ref} labelCol={{ flex: '80px' }} onFinish={d => changeSearch(d, params, setParams)} onReset={() => ref.current?.submit()}>
        <Row gutter={48}>
          <Col span={8}>
            <Item label='序列号' name='serieno'>
              <Input placeholder='请输入' allowClear />
            </Item>
          </Col>
          <Col span={8}>
            <Item label='案号' name='caseno_desc'>
              <Input placeholder='请输入' allowClear />
            </Item>
          </Col>
          <Col span={8}>
            <Item label='创建时间' name='date'>
              <DatePicker.RangePicker className={style.full} />
            </Item>
          </Col>
        </Row>
        <Row gutter={48}>
          <Col span={16} />
          <Col span={8} className={style.btns}>
            <Space>
              <Button type='primary' htmlType='submit'>查询</Button>
              <Button htmlType='reset'>重置</Button>
            </Space>
          </Col>
        </Row>
      </Form>
    </div>
  )
}

export default Main
